package com.speedtest.service;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class SpeedTestService {
    
    private static final Pattern SIZE_PATTERN = Pattern.compile("(\\d+)(?:mb|MB)?");
    private static final int MAX_SIZE_MB = 100;
    private static final int MIN_SIZE_MB = 1;
    private final SecureRandom random = new SecureRandom();
    
    public int parseSizeParameter(String sizeParam) throws IllegalArgumentException {
        Matcher matcher = SIZE_PATTERN.matcher(sizeParam);
        
        if (!matcher.matches()) {
            throw new IllegalArgumentException("Invalid size format. Use format: 1, 5mb, 10MB, etc.");
        }
        
        int sizeMB = Integer.parseInt(matcher.group(1));
        
        if (sizeMB < MIN_SIZE_MB || sizeMB > MAX_SIZE_MB) {
            throw new IllegalArgumentException(
                String.format("Size must be between %dMB and %dMB", MIN_SIZE_MB, MAX_SIZE_MB)
            );
        }
        
        return sizeMB;
    }
    
    public Resource generateTestData(int sizeMB) {
        long sizeBytes = (long) sizeMB * 1024 * 1024;
        byte[] data = new byte[(int) sizeBytes];
        
        // 填充随机数据以防止压缩优化
        random.nextBytes(data);
        
        // 添加一些模式以确保数据不可压缩
        for (int i = 0; i < data.length; i += 1024) {
            int remaining = Math.min(1024, data.length - i);
            byte[] pattern = generatePattern(i);
            System.arraycopy(pattern, 0, data, i, Math.min(pattern.length, remaining));
        }
        
        return new ByteArrayResource(data);
    }
    
    private byte[] generatePattern(int seed) {
        byte[] pattern = new byte[1024];
        SecureRandom patternRandom = new SecureRandom();
        patternRandom.setSeed(seed);
        patternRandom.nextBytes(pattern);
        return pattern;
    }
}